//
//  CZNetworkTool.swift
//  GZWeibo009
//
//  Created by gzxzmac on 16/3/21.
//  Copyright © 2016年 gzxzmac. All rights reserved.
//

import UIKit
import AFNetworking

// MARK: - 统一管理错误信息
enum CZNetworkToolError: Int {
    var netDomain: String {
        get {
            return "cn.itcast.error.net"
        }
    }
    
    var dbDomain: String {
        get {
            return "cn.itcast.error.db"
        }
    }
    
    case RepeatRefresh = -1
    case EmptyAccessToken = -250
    
    // 枚举里面可以有属性
    var errorDescription: String {
        get {
            switch self {
                case RepeatRefresh: return "嘿哥们,手不要那么快,重复刷新了"
                case EmptyAccessToken: return "access_token 没有值"
            }
        }
    }
    
    // 枚举可以有方法
    func error() -> NSError {
        return NSError(domain: netDomain, code: self.rawValue, userInfo: ["errorDescription" : self.errorDescription])
    }
}

class CZNetworkTool: NSObject {
    // 单例
    static let sharedInstance: CZNetworkTool = CZNetworkTool()  // 类里面是可以访问private的方法
    
    /// afn
    private let afnManager: AFHTTPSessionManager = AFHTTPSessionManager(baseURL: CZBaseURL)
    
    // 私有化构造函数
    private override init() {
        super.init()
        
        // 设置afn支持 text/plain类型
//        print("afnManager.responseSerializer.acceptableContentTypes: \(afnManager.responseSerializer.acceptableContentTypes)")
        afnManager.responseSerializer.acceptableContentTypes?.insert("text/plain")
    }
    
    // 如果在控制器或VM,直接调用AFN的方法,如果AFN以后不好用,想换其他的框架或者AFN升级,请求参数更换,到时候要更换的时候就非常麻烦
    /// 自己来封装GET请求
    func requestGET(URLString: String, var parameters: [String: AnyObject]?, requestCallback: (result: [String: AnyObject]?, error: NSError?) -> ()) {
        
        // 自己来拼接accessToken,外面不用传入accessToken
//        CZUserAccountViewModel.sharedInstance.userAccount?.access_token = nil
        guard let access_token = CZUserAccountViewModel.sharedInstance.userAccount?.access_token else {
//            CZPrint(msg: "access_token 没有值")
            // 告诉调用的人,没有access_token
//            let emptyAcc = CZNetworkToolError.EmptyAccessToken
//            let error = NSError(domain: "cn.itcast.error.net", code: emptyAcc.rawValue, userInfo: ["errorDescription" : emptyAcc.errorDescription])
            requestCallback(result: nil, error: CZNetworkToolError.EmptyAccessToken.error())
            return
        }
        
        // 如果没有传入参数,创建参数字典
        if parameters == nil {
            parameters = [String: AnyObject]()
        }
        
        parameters!["access_token"] = access_token
        
        afnManager.GET(URLString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
            // 网络请求回来的都是JSON格式
            let dict = result as? [String: AnyObject]
            requestCallback(result: dict, error: nil)
            }) { (_, error) -> Void in
                requestCallback(result: nil, error: error)
        }
    }
    
    /// 自己来封装POST请求, POST请求没有去封装access_token,因为不是所有的POST请求都需要access_token
    func requestPOST(URLString: String, parameters: AnyObject?, requestCallback: (result: [String: AnyObject]?, error: NSError?) -> ()) {
        afnManager.POST(URLString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
            // 网络请求回来的都是JSON格式
            let dict = result as? [String: AnyObject]
            requestCallback(result: dict, error: nil)
            }) { (_, error) -> Void in
                requestCallback(result: nil, error: error)
        }
    }
    
    /// 封装带formdata可以上内容的方法
    func requestPOST(URLString: String, parameters: [String: AnyObject], constructingBodyWithBlock: ((AFMultipartFormData) -> Void)?, requestCallback: (result: [String: AnyObject]?, error: NSError?) -> ()) {
        afnManager.POST(URLString, parameters: parameters, constructingBodyWithBlock: constructingBodyWithBlock, progress: nil, success: { (_, result) -> Void in
            let dict = result as? [String: AnyObject]
            requestCallback(result: dict, error: nil)
            }) { (_, error) -> Void in
                requestCallback(result: nil, error: error)
        }
    }
}
